//
//  Settings_TableVC.m
//  KaChing_App
//
//  Created by Jordan Robert Yust on 2/20/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "Settings_TableVC.h"
#import "Constants.h"

@implementation Settings_TableVC

@synthesize userDictionary;
@synthesize newProfile_VC;
@synthesize user_TableVC;
@synthesize updateProfile_VC;
@synthesize profileOptions_ActionSheet;
@synthesize selectedProfile_ProfileName;
@synthesize selectedProfile_UserID;
@synthesize selectedProfile_RemoteKey;
@synthesize deleteProfile_AlertView;
@synthesize userTableView;

// Implement viewDidLoad to do additional setup after loading the view.
- (void)viewDidLoad
{
	/* Some code for saving info between application launches (later implementation) */
	NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
	userDictionary = (NSMutableDictionary *)[preferences dictionaryForKey:@"UserDictionary"];
	
	/* If the userDictionary hasn't been created yet */
	if (userDictionary == nil)
	{
		/* Create a default entry */
		NSMutableArray *profileNames = [NSMutableArray arrayWithObjects:nil];
		NSMutableArray *userIDs = [NSMutableArray arrayWithObjects:nil];
		NSMutableArray *remoteKeys = [NSMutableArray arrayWithObjects:nil];
	
		/* Create the Dictionary object with the default values */
		userDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:
						  profileNames, @"ProfileNames",
						  userIDs, @"UserIDs",
						  remoteKeys, @"RemoteKeys", nil];
	}
	
    [super viewDidLoad];
}


- (void)dealloc
{
	/* Release all objects */
	[userDictionary release];
	[newProfile_VC release];
	[user_TableVC release];
	[updateProfile_VC release];
	[profileOptions_ActionSheet release];
	[selectedProfile_ProfileName release];
	[selectedProfile_RemoteKey release];
	[selectedProfile_UserID release];
	[deleteProfile_AlertView release];
    [super dealloc];
}

/*
 - (id)initWithStyle:(UITableViewStyle)style {
 // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
 if (self = [super initWithStyle:style]) {
 }
 return self;
 }
 */


/*
 ------------------------------------------------------------------------
 UITableViewDataSource Protocol methods
 ------------------------------------------------------------------------
 */

#pragma mark -
#pragma mark UITableViewDataSource Protocol methods

/*
 This method specifies how many sections there to be in the table.
 NOTE: This method is part of the UITableViewDataSource Protocol.
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

/*
 This method specifies the number of rows for each section.
 NOTE: This method is part of the UITableViewDataSource Protocol.
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[userDictionary objectForKey:@"ProfileNames"] count];
}

/*
 This method creates/modifies the cell at the specified index in the tableView.
 NOTE: This method is part of the UITableViewDataSource Protocol.
 The 'tableView' parameter is the actual UITableView object.
 The 'indexPath' parameter is the index in the tableView
 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	/* Obtain the UITableViewCell object at the specified index */
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }
	
	/* Assign the name of the cell to be the profile name at the specified index in the ProfileName array
	 of the UserDictionary */
	[cell setText:(NSString *)[[userDictionary objectForKey:@"ProfileNames"] objectAtIndex:indexPath.row]];
	
	/* Return the cell */
    return cell;
}

/*
 This method specifies the Header of the current section in the tableView.
 NOTE: This method is part of the UITableViewDataSource Protocol.
 */
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	return @"User Profiles";
}


/*
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 }
 if (editingStyle == UITableViewCellEditingStyleInsert) {
 }
 }
 */

/*
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 return YES;
 }
 */

/*
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 return YES;
 }
 */


/*
 ------------------------------------------------------------------------
 UITableViewDelegate Protocol methods
 ------------------------------------------------------------------------
 */

#pragma mark -
#pragma mark UITableViewDelegate Protocol methods

/*
 This method is called whenever an entry in a TableView is selected.
 NOTE: This method is part of the UITableViewDelegate Protocol.
 The 'tableView' parameter is the actual TableView object.
 The 'indexPath' parameter is the index of the row that was selected in the tableView
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	/* Deselects the profile at the specified path */
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	
	/* Memory Management: Since the three attrs are about to be reinitialized, need to release their
	 current values */
	[selectedProfile_ProfileName release];
	[selectedProfile_UserID release];
	[selectedProfile_RemoteKey release];
	
	/* Obtain the profile characteristics corresponding to the selected index in the table */
	selectedProfile_ProfileName = [[userDictionary objectForKey:@"ProfileNames"] objectAtIndex:indexPath.row];
	selectedProfile_UserID = [[userDictionary objectForKey:@"UserIDs"] objectAtIndex:indexPath.row];
	selectedProfile_RemoteKey = [[userDictionary objectForKey:@"RemoteKeys"] objectAtIndex:indexPath.row];
	
	/* Memory Management: Since the three attrs are used throughout this file, need to up the retain count
	 so that they don't accidently get deallocated. */
	[selectedProfile_ProfileName retain];
	[selectedProfile_UserID retain];
	[selectedProfile_RemoteKey retain];

	/* Create an actionSheet with the appropriate options for managing the profile */
	UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:[@"Profile: " stringByAppendingFormat:selectedProfile_ProfileName]
														delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil
														otherButtonTitles:@"Select Profile", @"Edit Profile", @"Delete Profile", nil];
	actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
	actionSheet.destructiveButtonIndex = 2;	// make the delete button red (destructive)
	[actionSheet showInView:self.view]; // show from our table view (pops up in the middle of the table)
	
	[profileOptions_ActionSheet release];
	profileOptions_ActionSheet = [actionSheet retain];
	[actionSheet release];
}



/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
}
*/
/*
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
*/

/*
 ------------------------------------------------------------------------
UIActionSheetDelegate methods
 ------------------------------------------------------------------------
 */

#pragma mark -
#pragma mark UIActionSheetDelegate methods

/*
 This method is called whenever a button in an ActionSheet is clicked in the current view. 
 NOTE: This method is part  of the UIActionSheetDelegate protocol.
 The 'actionSheet' parameter is the actual ActionSheet object.
 The 'buttonIndex' parameter is the index number of the button that was pressed in the ActionSheet.
 */
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	/* If the actionSheet is the one used in displaying options for selecting a profile */
	if (actionSheet == profileOptions_ActionSheet)
	{
		/* If the option was to SELECT the profile... */
		if (buttonIndex == selectProfile_ActionSheetIndex)
		{
			/* Call the method */
			self.selectProfile;
		}
		/* If the option was to EDIT the profile... */
		else if (buttonIndex == editProfile_ActionSheetIndex)
		{
			/* Call the method */
			self.editProfile;
		}
		/* If the option was to DELETE the profile... */
		else if (buttonIndex == deleteProfile_ActionSheetIndex)
		{
			/* Call the method */
			self.deleteProfile;
		}
	}
}

/*
 This method is called when the user selects the "Select Profile" button 
 from the ActionSheet.  It allows the user to select the profile in order to 
 obtain the profile's account-specific data.
 */
- (void) selectProfile
{
	/* If the VC used in displaying the selected profile hasn't been created yet... */
	if (self.user_TableVC == nil)
	{
		/* Create the VC via the nib file */
		UserAttr_TableVC *tempController = [[UserAttr_TableVC alloc]
											initWithNibName:@"UserAttr_TableVC"
											bundle:[NSBundle mainBundle]];

		self.user_TableVC = tempController;
		[tempController release];
	}
	
	/* sets the table's title to be the user profile's name */
	self.user_TableVC.title = selectedProfile_ProfileName;
	
	/* Push the view controller onto the navigation controller's stack.  This transitions to the new view */
	[self.navigationController pushViewController:user_TableVC animated:YES];
	
	/* Pass the selected profile's characteristics to their corresponding fields in the VC */
	[self.user_TableVC setProfileName:selectedProfile_ProfileName];
	[self.user_TableVC setUserID:selectedProfile_UserID];
	[self.user_TableVC setRemoteKey:selectedProfile_RemoteKey];
	
	/* Reloads the data with the current user information */
	[self.user_TableVC reloadTheData];
}

/*
 This method is called when the user selects the "Edit Profile" button from the ActionSheet.  It allows the user to edit
 the selected profile.
 */
- (void) editProfile
{
	/* Obtain the index in the dictionary where the profile to be updated exists */
	NSInteger indexToUpdate = [[userDictionary objectForKey:@"UserIDs"] indexOfObject:selectedProfile_UserID];
	
	/* If the UpdateProfile view controller hasn't been created yet... */
	if (self.updateProfile_VC == nil)
	{
		/* Create the view controller via the nib file */
		UpdateProfile_VC *viewController = [[UpdateProfile_VC alloc] 
											initWithNibName:@"UpdateProfile_VC"
											bundle:[NSBundle mainBundle]];
		self.updateProfile_VC = viewController;
		[viewController release];
	}
	
	self.updateProfile_VC.title = @"Update Profile";	// Specify the title
	
	/* Pass various fields to the view controller that it will need */
	[self.updateProfile_VC setIndexToUpdate:(NSInteger *)indexToUpdate];
	[self.updateProfile_VC setUserDictionary:userDictionary];
	[self.updateProfile_VC setSettings_TableView:self.userTableView];
	
	/* Push the view controller onto the navigation controller's stack.  This transitions to the new view */
	[self.navigationController pushViewController:updateProfile_VC animated:YES];
	
	/* Set the text of each of the view's textFields to be the names of their corresponding profile characteristics. */
	[[self.updateProfile_VC profileName_TextField] setText:selectedProfile_ProfileName];
	[[self.updateProfile_VC userID_TextField] setText:selectedProfile_UserID];
	[[self.updateProfile_VC remoteKey_TextField] setText:selectedProfile_RemoteKey];
	
	/* ResignFirstResponder for all text fields (ensures that keyboard is hidden upon initial view display) */
	[[self.updateProfile_VC profileName_TextField] resignFirstResponder];
	[[self.updateProfile_VC userID_TextField] resignFirstResponder];
	[[self.updateProfile_VC remoteKey_TextField] resignFirstResponder];
}

/*
 This method is called when the user selects the "Delete Profile" button from the ActionSheet.  It allows the
 user to delete the selected profile.
 */
- (void) deleteProfile
{
	/* Displays an AlertView to verify user wants to delete the profile */
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Are you sure you want to delete this profile?"
												   delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Yes", nil];
	[alert show];
	
	deleteProfile_AlertView = alert;
	[alert release];
}

/*
 ------------------------------------------------------------------------
UIAlertViewDelegate methods
 ------------------------------------------------------------------------
 */

#pragma mark -
#pragma mark UIAlertViewDelegate methods

/*
 This method is called whenever a button in an AlertView is clicked in the current view. 
 NOTE: This method is part  of the UIAlertViewDelegate protocol.
 The 'alertView' parameter is the actual AlertView object.
 The 'buttonIndex' parameter is the index number of the button that was pressed in the AlertView.
 */
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	/* If the AlertView being displayed corresponds to the one that appears when the user wants to delete
	 a profile. */
	if (alertView == deleteProfile_AlertView)
	{
		/* If the index in the AlertView corresponds to the "Yes" button (meaning the user DOES want to
		 delete the profile)... */
		if (buttonIndex == 1)
		{
			/* If the dictionary of users exists (should always be the case in this situation)... */
			if (userDictionary != nil)
			{
				/* Obtain the index in the dictionary where the profile to be deleted exists */
				NSInteger indexToDelete = [[userDictionary objectForKey:@"ProfileNames"] indexOfObject:selectedProfile_ProfileName];
				
				/* Delete the object at the index in each of the three arrays (profileName, UserID, RemoteKey).
				 NOTE: These three lines are what perform the actual deletion. */
				[[userDictionary objectForKey:@"ProfileNames"] removeObjectAtIndex:indexToDelete];
				[[userDictionary objectForKey:@"UserIDs"] removeObjectAtIndex:indexToDelete];
				[[userDictionary objectForKey:@"RemoteKeys"] removeObjectAtIndex:indexToDelete];
				
				/* Reload the text in the view's table (thus not showing the recently deleted profile */
				[self.userTableView reloadData];
				
				/* Resets the user defaults (so that the deleted profile will not appear again upon application relaunching) */
				NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];		
				[preferences setObject:userDictionary forKey:@"UserDictionary"];
			}
		}
	}
}

/*
 ------------------------------------------------------------------------
IBAction methods
 ------------------------------------------------------------------------
 */

#pragma mark -
#pragma mark IBAction methods

/*
 This method is called whenever the user wants to add a new profile.  It transitions to the view to
 add a new profile.
*/
- (IBAction) addNewProfile:(id) sender
{
	/* Create the view controller via the nib file */
	AddNewProfile_VC *viewController = [[AddNewProfile_VC alloc] 
										initWithNibName:@"AddNewProfile_VC"
										bundle:[NSBundle mainBundle]];
	[self setNewProfile_VC:viewController];
	[viewController release];
	
	/* Passing along various fields to the AddNewProfile View Controller (VC) that
	 it will need/use. */
	[newProfile_VC setUserDictionary:userDictionary];
	[newProfile_VC setSettings_TableView:self.userTableView];
	
	// Push the view controller on to the stack.  This transitions to the addNewProfile view
	[self.navigationController pushViewController:self.newProfile_VC animated:YES];
		
	self.newProfile_VC.title = @"Add New Profile";	// Specify the title of the view
}

@end

